<template>
	<view :style="colorStyle">
		<view class="navbar acea-row row-around">
			<view class="item acea-row row-center-wrapper" :class="{ on: navOn === 1 }" @click="onNav(1)">{{$t(`未使用`)}}
			</view>
			<view class="item acea-row row-center-wrapper" :class="{ on: navOn === 2 }" @click="onNav(2)">
				{{$t(`已使用/过期`)}}
			</view>
		</view>
		<view class='coupon-list' v-if="couponsList.length">
			<view class='item acea-row row-center-wrapper' v-for='(item,index) in couponsList' :key="index"
				 @click="useCoupon(item)">
				<view class="moneyCon acea-row row-center-wrapper">
					<view class='money' :class='item.status==1 ? "" : "moneyGray"'>
						<view>{{$t(`车服权益`)}}</view>
					</view>
				</view>
				<view class='text'>
					<view class='condition'>
						<view class="name line2">
							<!-- <view class="line-title" :class="item._type === 0 ? 'bg-color-huic' : 'bg-color-check'"
								v-if="item.applicable_type === 0">{{$t(`通用劵`)}}</view>
							<view class="line-title" :class="item._type === 0 ? 'bg-color-huic' : 'bg-color-check'"
								v-else-if="item.applicable_type === 1">{{$t(`品类券`)}}</view>
							<view class="line-title" :class="item._type === 0 ? 'bg-color-huic' : 'bg-color-check'"
								v-else>{{$t(`商品券`)}}</view> -->
							<!-- <image src="../../../static/images/fvip.png" class="pic" v-if="item.receive_type===4">
							</image> -->
							{{$t(item.title)}}
						</view>
					</view>
					<view class='data acea-row row-between-wrapper'>
						<view>{{"使用期限："}}{{item.expire_time == null?"永久":getTime(1,item.expire_time)}}</view>
						
						<view class='bnt bg-color' v-if="item.status==1">{{$t(`立即使用`)}}</view>
						<view class='bnt gray' v-else>{{$t(`已过期`)}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class='noCommodity' v-if="!couponsList.length && page === 2">
			<view class='pictrue'>
				<image :src="imgHost + '/statics/images/noCoupon.png'"></image>
			</view>
		</view>
		<view class='denglu' >
			<view  @click="denglu()">
				登录
			</view>
		</view>
		<!-- #ifdef MP -->
		<!-- <authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize> -->
		<!-- #endif -->
		<!-- #ifndef MP -->
		<home></home>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		getUserCoupons,
		getUserChefuquanyi,
		getUserNologinrequired
	} from '@/api/api.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	import home from '@/components/home';
	import colors from '@/mixins/color.js';
	import CryptoJS from'@/components/verify/utils/crypto-js.js';
	
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	export default {
		components: {
			// #ifdef MP
			authorize,
			// #endif
			home
		},
		mixins: [colors],
		data() {
			return {
				imgHost: HTTP_REQUEST_URL,
				couponsList: [],
				loading: false,
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				navOn: 1,
				page: 1,
				limit: 15,
				finished: false
			};
		},
		computed: mapGetters(['isLogin']),
		watch: {
			isLogin: {
				handler: function(newV, oldV) {
					if (newV) {
						this.getUseCoupons();
					}
				},
				deep: true
			}
		},
		onLoad() {
			if (this.isLogin) {
				this.getUseCoupons();
			} else {
				toLogin();
			}
		},
		onReachBottom() {
			this.getUseCoupons();
		},
		methods: {
			onNav: function(type) {
				this.navOn = type;
				this.couponsList = [];
				this.page = 1;
				this.finished = false;
				this.getUseCoupons();
			},
			denglu(){
				console.log("denglu11111")
				let to_url="https://www.xiaokunkeji.cn/user/index.html/pages/home/newIndex"
				let url = `/pages/goods_cate_details/details/index?url=${encodeURIComponent(to_url)}`;
				uni.navigateTo({
					url: url
				});
				
				// this.testUrl();
				  
			},
			useCoupon(item) {
				if (this.navOn == 2) return
				// let to_url="https://www.xiaokunkeji.cn/user/index.html/pages/voucher/details?type=5&serviceTicketCode=051659050514356";
				let to_url=item.to_url
				// let to_url="https://www.xiaokunkeji.cn/user/index.html/pages/home/newIndex"
				let url = `/pages/goods_cate_details/details/index?url=${encodeURIComponent(to_url)}`;
				
				console.log("1111111",item)
				if(item.to_url==null){
					//======免登录
					
					getUserNologinrequired({
						platform_order_no: item.platform_order_no,
					}).then(res => {
						that.loading = false;
						uni.hideLoading();
						console.log("------quanfucheyi:",res)
						uni.navigateTo({
							url: res.data
						});
					}).catch(err => {
						that.loading = false;
						uni.showToast({
							title: err,
							icon: 'none'
						});
					});
					//==========
				}else{
					uni.navigateTo({
						url: url
					});
				}
				
				
				
				
				
				// this.handleOpenExternalLink()
				
				
			},
			handleOpenExternalLink() {
			    const externalUrl = "https://baidu.com"; // 替换成你的H5链接
				wx.miniapp.openUrl({
					
				})
			    wx.showModal({
			      title: '提示',
			      content: '该页面需要在浏览器中打开，你可以：1. 复制链接后手动打开浏览器2. 点击“直接打开”（部分浏览器支持）',
			      confirmText: '复制链接',
			      success(res) {
			        if (res.confirm) {
			          // 用户点击“复制链接”
			          wx.setClipboardData({
			            data: externalUrl,
			            success() {
			              wx.showToast({
			                title: '链接已复制',
			                icon: 'success',
			              });
			              // 可提示用户去浏览器粘贴打开
			              // setTimeout(() => {
			              //   wx.showModal({
			              //     title: '提示',
			              //     content: '链接已复制，请粘贴到浏览器打开',
			              //     showCancel: false,
			              //   });
			              // }, 1000);
			            },
			          });
			        }
			      },
			    });
			  },
			/**
			 * 授权回调
			 */
			onLoadFun: function() {
				this.getUseCoupons();
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e
			},
			/**
			 * 获取领取优惠券列表
			 */
			getUseCoupons: function() {
				let that = this;
				if (that.loading || that.finished) {
					return;
				}
				that.loading = true;
				uni.showLoading({
					title: that.$t(`正在加载…`)
				});
				
				getUserChefuquanyi({
					page: this.page,
					limit: this.limit,
					status: this.navOn,
				}).then(res => {
					that.loading = false;
					uni.hideLoading();
					console.log("------quanfucheyi:",res)
					that.couponsList = that.couponsList.concat(res.data);
					that.finished = res.data.length < that.limit;
					that.page += 1;
				}).catch(err => {
					that.loading = false;
					uni.showToast({
						title: err,
						icon: 'none'
					});
				});
				//=====================
			},
			
			getTime(type,value){
				if(type == 1){
					let values=value.split(" ")
					if(values.length>1){
						return values[0]
					}
				}else if(type == 2){
					return value
				}
				return value
			},
			
			testUrl(){
				// 配置参数
				const url= "http://open.yiqida.cn/api/UserCommdity/GetCommodityInfo";
				const timestamp = Date.now(); // 13位毫秒时间戳
				const key = "e8fb808da094790d246083eda6517445"; // 替换为你的密钥
				const userName = "ximaqiche"; // 登录账号
				const bodyData = { id: 10000221 }; // 请求体JSON参数
				
				// 1. 生成无空格JSON字符串
				const bodyJson = JSON.stringify(bodyData, null, 0);
				console.log("请求体JSON:", bodyJson); // {"id":10000221}
				
				// 2. 生成签名字符串 (timestamp + bodyJson + key)
				const stringToSign = timestamp + bodyJson + key;
				console.log("待签名字符串:", stringToSign);
				
				// 3. 计算MD5签名
				const sign = CryptoJS.MD5(stringToSign).toString();
				console.log("--签名结果:", sign);
				
				  
				  wx.request({
				    url: `${url}?timestamp=${timestamp}&userName=${userName}&sign=${sign}`,
				    method: 'POST',
				    header: {
				      'Content-Type': 'application/json'
				    },
				    data: bodyJson, // 请求体
				    success(res) {
				      console.log('响应数据:', res.data)
				    },
				    fail(error) {
				      console.error('请求失败:', error)
				    }
				  })
			},
			
		}
	}
</script>

<style>
	.money {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.pic-num {
		color: #ffffff;
		font-size: 24rpx;
	}
	.coupon-list .item{
	}
	.coupon-list .item .text{
		padding: 14rpx 10rpx;
	}
	.coupon-list .item .text .condition {
		display: flex;
	}

	.coupon-list .item .text .condition .name {
		font-size: 24rpx;
		font-weight: 500;
		line-height: 44rpx;
		/* display: flex;
		align-items: center; */
	}
	.denglu {
		margin-top: 1500rpx;
		margin-left: 600rpx;
	}
	.coupon-list .item .text .condition .pic {
		width: 30rpx;
		height: 30rpx;
		display: block;
		margin-right: 10rpx;
		display: inline-block;
		vertical-align: middle;
	}

	.condition .line-title {
		/* width: 70rpx; */
		height: 36rpx !important;
		padding: 0 5px;
		line-height: 32rpx;
		text-align: center;
		box-sizing: border-box;
		background: rgba(255, 247, 247, 1);
		border: 1px solid var(--view-theme);
		opacity: 1;
		border-radius: 20rpx;
		font-size: 18rpx !important;
		color: var(--view-theme);
		margin-right: 12rpx;
		text-align: center;
		display: inline-block;
		vertical-align: middle;
	}

	.condition .line-title.bg-color-huic {
		border-color: #BBB !important;
		color: #bbb !important;
		background-color: #F5F5F5 !important;
	}
</style>

<style lang="scss" scoped>
	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 90rpx;
		background-color: #FFFFFF;
		z-index: 9;

		.item {
			border-top: 5rpx solid transparent;
			border-bottom: 5rpx solid transparent;
			font-size: 30rpx;
			color: #999999;
			
			&.on {
				border-bottom-color: var(--view-theme);
				color: #282828;
			}
		}
	}

	.coupon-list {
		margin-top: 122rpx;
	}

	.noCommodity {
		margin-top: 300rpx;
	}
</style>
